<?php

namespace app\service;

use app\core\exception\BusinessException;
use app\core\Service;
use app\model\Banner;
use think\facade\Db;

/**
 * @extends Service<BannerService>
 */
class BannerService extends Service
{

    public function getList($page, $limit, $searchQuery = null)
    {
        $w = [];
        if (!empty($searchQuery['title']) && $searchQuery['title'] != '') {
            $w[] = ['title', 'like', "%" . $searchQuery['title'] . "%"];
        }
        if (!empty($searchQuery['type']) && $searchQuery['type'] != '') {
            $w[] = ['type', '=', $searchQuery['type']];
        }
        $category = Banner::where($w)->page($page, $limit)->order('sort desc');
        return [
            'total' => $category->count(),
            'list' => $category->select(),
        ];
    }

    public function save($data, $id = null)
    {
        Db::startTrans();
        try {
            if (empty($id)) {
                Banner::create([
                    'title' => $data['title'],
                    'img_url' => $data['img_url'],
                    'url' => $data['url'],
                    'sort' => $data['sort'],
                ]);
            } else {
                $info = Banner::where('id', $id)->find();
                if (empty($info)) {
                    throw new \Exception('数据不存在');
                }
                $info->save([
                    'title' => $data['title'],
                    'img_url' => $data['img_url'],
                    'url' => $data['url'],
                    'sort' => $data['sort'],
                ]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new BusinessException($e->getMessage());
        }

        return true;

    }

    public function del($id)
    {
        $info = Banner::where('id', $id)->find();
        if (!$info) {
            throw new BusinessException('数据不存在');
        }
        return $info->delete();
    }
}